package zmee.print;

import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.utils.ObjectUtils;
import kd.bos.ksql.util.StringUtil;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.print.core.data.DataRowSet;
import kd.bos.print.core.data.datasource.CustomDataSource;
import kd.bos.print.core.data.field.*;

import kd.bos.print.core.plugin.AbstractPrintPlugin;
import kd.bos.print.core.plugin.event.*;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import zmee.bid.oa.OAutil;

import java.math.BigDecimal;

import java.text.SimpleDateFormat;
import java.util.*;

public class ChangeFieldsPrintPlugiin extends AbstractPrintPlugin {
    private static Log logger = LogFactory.getLog(ChangeFieldsPrintPlugiin.class);
    static String billno = "";
    static String entityName="";
    @Override
    public void loadCustomData(CustomDataLoadEvent evt) {
        super.loadCustomData(evt);
        CustomDataSource dataSource = evt.getDataSource();
//        List<DataRowSet> customDataRows1 = evt.getCustomDataRows();
        if(StringUtil.equals("src_decision",entityName)) {
            dataSource.getQueryField();
            switch (dataSource.getDsName()){
                case "zbxj":
                    //定标单
                    DynamicObject decision = BusinessDataServiceHelper.loadSingle(entityName, "id,billno,creator,createtime", new QFilter("billno", QCP.equals, billno).toArray());
                    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        //公告时间
                        Object billdate = (Date) getSunField("src_publishnotice", billno, "src_sourcenotice", "billdate");
                        String ggsj = sf.format(billdate);
                        //招标地点
                    Map<String, String> timeSite = getTimeSite(billno);

                    //会议主持-项目负责人
                    Object sunField = getSunField2("src_bidopen", billno, "src_project_reference", "entryentity.bizrole", "JS0001");
                    logger.info("==hyzc0==:"+sunField);
                    String hyzc=getNameString(sunField);
                    if( hyzc==null || "".equals(hyzc)){
                        Object sunField21 = getSunField2("src_bidopen", billno, "src_project_reference", "entryentity.bizrole", "SYS001");
                        hyzc = getNameString(sunField21);
                        logger.info("==hyzc1==:"+sunField21);
                    }
                    logger.info("==hyzc==:"+sunField);
                        //评审小组成员
                        Object sunField22 = getSunField2("src_bidopen", billno, "src_project_reference", "entryentity.bizrole", "SYS011");
                        String psxz = getNameString(sunField22);
                        //监督小组
                        getSunField2("src_bidopen", billno, "src_project_reference", "entryentity.bizrole", "SYS022");
                        //中标供应商
                        String supplierName = getSupplierName(decision.getString("id"));

                        String jdxz=getBizrole(billno);
                    logger.info("=====jdxz====="+jdxz);
                    List<DataRowSet> customDataRows = evt.getCustomDataRows();
                        DataRowSet dataRowSet = new DataRowSet();
                        dataRowSet.put("gssj", new TextField(ggsj));//公告时间
                        dataRowSet.put("psxz", new TextField(psxz));//评审小组
                        dataRowSet.put("hyzc", new TextField(hyzc));//会议主持
                        dataRowSet.put("kbsj", new TextField(timeSite.get("time")));//开标时间
                        dataRowSet.put("zbdd", new TextField(timeSite.get("site")));//招标地点
                        dataRowSet.put("zbgys", new TextField(supplierName));//中标供应商
                        DynamicObject creator = decision.getDynamicObject("creator");
                        if(creator != null) {
                            dataRowSet.put("tbr", new TextField(creator.getString("name")));//填报人
                        }
                        if(jdxz != null){
                            dataRowSet.put("jdxz", new TextField(jdxz));//监督小组
                        }
                        dataRowSet.put("sj", new TextField(decision.getString("createtime")));//时间
                        customDataRows.add(dataRowSet);
                    break;
            }
        }
    }



    @Override
    public void afterLoadData(AfterLoadDataEvent evt) {
        super.afterLoadData(evt);
        String dsName = evt.getDataSource().getDsName();

        List<DataRowSet> dataRowSets = evt.getDataRowSets();
        for (DataRowSet dataRowSet : dataRowSets) {
            if (StringUtil.equals("src_decision",dsName)){
                billno = (String) dataRowSet.getField("billno").getValue();
                entityName=dsName;
            }
            if (StringUtil.equals("src_decisionsum_sup",dsName)){//中部金额汇总
                //根据供应商获取 一次报价
                CollectionField entryentity = dataRowSet.getCollectionField("entryentity");
                List<DataRowSet> entryentityValue = entryentity.getValue();
                for (DataRowSet rowSet : entryentityValue) {
                    Field supplierfield = rowSet.getField("supplier.id");
                    Field amount = rowSet.getField("amount");//中标未税金额——一次报价
                    Field preorderratio = rowSet.getField("preorderratio");//预定标未税占比(%)——商务评分
                   Long supplierid = (Long) supplierfield.getValue();
                    //获取父单据
                    DynamicObject xyxmDynamicObject = BusinessDataServiceHelper.loadSingle("src_projectf7", "id",
                            new QFilter[]{new QFilter("billno", QCP.equals, billno)});
                    //取通用报价单首轮的含税单价
                    DynamicObject query = QueryServiceHelper.queryOne("src_purlist_stand", "entryentity.taxprice",
                            new QFilter[]{new QFilter("entryentity.supplier", QCP.equals, supplierid)
                                    .and("entryentity.turns", QCP.equals, "1")
                                    .and("entryentity.project",QCP.equals,xyxmDynamicObject.getPkValue())});
                    if (!ObjectUtils.isEmpty(query)){
                        BigDecimal ycbj = (BigDecimal) query.get(0);
                        amount.setValue(ycbj);
                    }
                    //一次商务评分
                    //取定标单分录“评标结果”对应供应商首轮报价的商务分
                    DynamicObjectCollection swpfquery = QueryServiceHelper.query("src_bidassess_log", "entryentity.bizscore,createtime",
                            new QFilter[]{new QFilter("entryentity.supplier", QCP.equals, supplierid)
                                    .and("projectf7", QCP.equals, xyxmDynamicObject.getPkValue())}, "createtime");
                    if (!ObjectUtils.isEmpty(swpfquery)){
                        DynamicObject dynamicObject = swpfquery.get(1);//默认取倒数第二行的评标结果
                        BigDecimal swpf = (BigDecimal) dynamicObject.get(0);
                        preorderratio.setValue(swpf);
                    }


                }
            }

            if (StringUtil.equals("src_bidassess_biz",dsName)) {//评标结果
                //标书编制
                DynamicObject load = BusinessDataServiceHelper.loadSingle(entityName, "id,sourcetype", new QFilter("billno", QCP.equals, billno).toArray());
                DynamicObject sourcetype = load.getDynamicObject("sourcetype");
                switch (sourcetype.getString("number")) {
                    //竞争性谈判
                    case "C010406":
                    //竞争性磋商
                    case "C010415":
                        //供应商ID
                        String supplier = dataRowSet.getField("supplier.id").toString();
                        //获取父单据
                        QFilter qFilter = new QFilter("turns", QCP.equals, "1")
                                .and("project.billno", QCP.equals, billno)
                                .and("entrystatus", QCP.in, new String[]{"C", "D"})
                                .and("supplier.id", QCP.equals, supplier);
                        DynamicObject[] analysetools = BusinessDataServiceHelper.load("src_analysetool", "id",
                                qFilter.toArray());
                        BigDecimal mount = new BigDecimal("0");
                        for (DynamicObject analy : analysetools) {
                            DynamicObject setool = BusinessDataServiceHelper.loadSingle(analy.getPkValue(), analy.getDynamicObjectType().getName());
                            mount = mount.add(setool.getBigDecimal("taxamount"));
                        }
                        Map<String, String> map = getMount(billno, supplier);
                        dataRowSet.put("ycbj", new TextField(mount.divide(new BigDecimal("10000"),5,BigDecimal.ROUND_HALF_UP).toString()));//一次报价
                        dataRowSet.put("swfyc", new TextField(map.get("bizscore")));//商务分一次
                        dataRowSet.put("zhfyc", new TextField(map.get("sumscore")));//综合分一次
                        dataRowSet.put("zmee_rank", new TextField(map.get("rank")));// 一次报价排名
                        break;
                    //招标
                    case "C010405":
                        break;

                    //询价
                    case "C010418":
                        break;
                    default:
                        break;
                }
            }

        }

    }


    private String getNameString(Object sunField22) {
        StringBuffer stringBuffer = new StringBuffer("");
        String psxz = "";
        if (!ObjectUtils.isEmpty(sunField22)){
            DynamicObjectCollection sunField22DC = (DynamicObjectCollection) sunField22;
//            DynamicObject dynamicObject = sunField22DC.get(0);
//            DynamicObject user = BusinessDataServiceHelper.loadSingle("bos_user","id,name,number",
//                    new QFilter[]{new QFilter("id",QCP.equals,dynamicObject.get(0))});
//            psxz = user.getString("name.zh_CN");
            ArrayList<String> names = new ArrayList<>();
            for (int i = 0; i < sunField22DC.size(); i++) {
                DynamicObject dynamicObject = sunField22DC.get(i);
                DynamicObject user = BusinessDataServiceHelper.loadSingle("bos_user","id,name,number",
                        new QFilter[]{new QFilter("id",QCP.equals,dynamicObject.get(0))});
                String string = user.getString("name.zh_CN");
                if (ObjectUtils.isEmpty(names)){
                    names.add(string);
                }else {
                    if (!names.contains(string)){
                        names.add(string);
                    }
                }
            }
            if (!ObjectUtils.isEmpty(names)){
                for (int i = 0; i < names.size(); i++) {
                    stringBuffer.append(names.get(i));
                    if (i<names.size()-1){
                        stringBuffer.append(",");
                    }
                    psxz = stringBuffer.toString();
                }
            }
        }
        return psxz;
    }


    private Object getSunField(String pentitykey,String billno,String sentrykey,String fieldKey) {
        Object fieldValue = null;
        DynamicObject sunDynamicObject = null;
        DynamicObject parentDynamicObject = BusinessDataServiceHelper.loadSingle(pentitykey, "id", new QFilter[]{new QFilter("billno", QCP.equals, billno)});
        if (!ObjectUtils.isEmpty(parentDynamicObject)){
            //根据招标公告id找招标公告组件里的时间
            sunDynamicObject = BusinessDataServiceHelper.loadSingle(sentrykey, fieldKey, new QFilter[]{new QFilter("pentitykey", QCP.equals, pentitykey).and("parentid", QCP.equals, parentDynamicObject.getPkValue())});
            if (!ObjectUtils.isEmpty(sunDynamicObject)){
                fieldValue =sunDynamicObject.get(fieldKey);
            }

        }
        return fieldValue;
        
    }

    private Map<String,String> getTimeSite(String billnoy){
        Map<String,String> map=new HashMap();
        DynamicObject bidopen = BusinessDataServiceHelper.loadSingle("src_bidopen", "id,time,site", new QFilter("billno", QCP.equals, billnoy).toArray());
        map.put("time",bidopen.getString("time"));//开标时间
        map.put("site",bidopen.getString("site"));//开标地点
        return map;
    }

    private Object getSunField2(String pentitykey,String billno,String sentrykey,String entryKey, String entryValue) {
        Object fieldValue = null;
        DynamicObject sunDynamicObject = null;
        DynamicObject parentDynamicObject = BusinessDataServiceHelper.loadSingle(pentitykey, "id", new QFilter[]{new QFilter("billno", QCP.equals, billno)});
        if (!ObjectUtils.isEmpty(parentDynamicObject)){
            //查询业务角色
            DynamicObject yejsDynamicObject = BusinessDataServiceHelper.loadSingle("pds_bizrole", "id", new QFilter[]{new QFilter("number", QCP.equals, entryValue)});
            //根据招标公告id找招标公告组件里的时间
            fieldValue = QueryServiceHelper.query(sentrykey, "entryentity.bidder,entryentity.project", new QFilter[]{new QFilter("entryentity.bizrole", QCP.equals,yejsDynamicObject.getPkValue())
                    .and("parentid",QCP.equals,parentDynamicObject.getPkValue())});

//            fieldValue = BusinessDataServiceHelper.loadSingle(sentrykey, fieldKey, new QFilter[]{new QFilter("pentitykey", QCP.equals, pentitykey)
//                    .and("parentid", QCP.equals, parentDynamicObject.getPkValue())
//                    .and("entryentity.bizrole",QCP.equals,"")});


        }
        return fieldValue;

    }

    //一次报价
    private Map<String,String> getMount(String bill , String supplierid ){
        DynamicObject[] load = BusinessDataServiceHelper.load("src_bidassess_log", "id,createtime", new QFilter("projectf7.billno", QCP.equals, bill).toArray(),"createtime desc");
        BigDecimal mount=new BigDecimal("0");
        Map<String,String> map=new HashMap();
        if(load.length > 1){
            for (int i = 0; i < load.length ; i++) {
                DynamicObject bidassess = BusinessDataServiceHelper.loadSingle(load[i].getPkValue(), "src_bidassess_log");
                DynamicObjectCollection entryentity = bidassess.getDynamicObjectCollection("entryentity");
                Boolean flag = true;
                for (int j = 0; j < entryentity.size(); j++) {
                    if (entryentity.get(j).getString("supplier.id").equals(supplierid)) {
                        logger.info("===supplierid===" + supplierid);
                        BigDecimal bizscore = entryentity.get(j).getBigDecimal("bizscore");
                        BigDecimal sumscore = entryentity.get(j).getBigDecimal("sumscore");
                        // 未税金额合计
                        BigDecimal locamount = entryentity.get(j).getBigDecimal("locamount");
                        // 含税金额合计
                        BigDecimal loctaxamount = entryentity.get(j).getBigDecimal("loctaxamount");
                        logger.info("===bizscore===" + bizscore + "   ===sumscore===" + sumscore);
                        map.put("mount", mount.toString());
                        if (locamount.compareTo(new BigDecimal("10000")) < 0) {
                            continue;
                        }
                        if (loctaxamount.compareTo(new BigDecimal("10000")) < 0) {
                            continue;
                        }
                        if ("0E-10".equals(sumscore.toString()) || sumscore.compareTo(new BigDecimal("1"))==0) {
                           continue;
                        } else {
                            map.put("sumscore", sumscore.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                        }
                        if ("0E-10".equals(bizscore.toString()) || bizscore.compareTo(new BigDecimal("1"))==0) {
                            continue;
                        } else {
                            map.put("bizscore", bizscore.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                        }
                        if (flag) {
                            // 一次报价排名
                            map.put("rank", String.valueOf(entryentity.get(j).getLong("rank")));
                            flag = false;
                        }
                    }
                }
            }
        }
        return map;
    }

    private String getSupplierName(String id){
        DynamicObject decisionsum = BusinessDataServiceHelper.loadSingle("src_decisionsum_sup", "id,parentid", new QFilter("parentid", QCP.equals, id).toArray());
        DynamicObject[] decisionsumsup = BusinessDataServiceHelper.load("src_decisionsumsup", "id,supplier,parentid,billid", new QFilter("billid", QCP.equals, decisionsum.getPkValue()).toArray());
        StringBuilder supplierName=new StringBuilder();
        for (int i = 0; i < decisionsumsup.length; i++) {
            supplierName.append("【"+decisionsumsup[i].getString("supplier.name")+"】");
        }
        return supplierName.toString();
    }

    private String getBizrole(String bill){
        //项目启动单
        DynamicObject project = BusinessDataServiceHelper.loadSingle("src_project", "id", new QFilter("billno",QCP.equals, bill).toArray());
        QFilter qFilter=new QFilter("parentid", QCP.equals,project.getPkValue())
                .and("entitykey", QCP.equals,"src_project_man");
        DynamicObject projectMan = BusinessDataServiceHelper.loadSingle("src_project_man", "id,entryentity,bizrole,bidder", qFilter.toArray());
        String jdxz="";
        logger.info("====projectMan===="+projectMan+project.getPkValue());
        if(projectMan!=null){
            DynamicObjectCollection entryentity = projectMan.getDynamicObjectCollection("entryentity");
            logger.info("====entryentity===="+entryentity.size());
            for (int i = 0; i < entryentity.size(); i++) {
                DynamicObject bizrole = entryentity.get(i).getDynamicObject("bizrole");//角色
                DynamicObject bidder = entryentity.get(i).getDynamicObject("bidder");//人员
                logger.info("====number===="+bizrole.getString("number"));
                switch (bizrole.getString("number")) {
                    case "SYS022":
                        if(!"".equals(jdxz)){
                            jdxz=jdxz+",";
                        }
                        jdxz=jdxz+bidder.getString("name");
                        break;
                }
            }
        }
        return jdxz;
    }
}


